<?php
/**
 * Ueditor 上传
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/12
 * Time: 14:11
 */

namespace app\admin\controller;

use app\common\controller\AdminBase;
use base\Uploader;
use think\Config;

class Ueditor extends AdminBase
{
    /**
     * ueditor 配置文件
     * @var array|mixed
     */
    protected $config = [];

    /**
     * 构造方法
     * Ueditor constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->config = Config::get('ueditor');
    }

    /**
     * 默认入口
     */
    public function index()
    {
        date_default_timezone_set("Asia/chongqing");
        error_reporting(E_ERROR);
        header("Content-Type: text/html; charset=utf-8");

        $action = $this->request->param('action');

        $result = [];
        switch ($action) {
            case 'config':
                $result = json_encode($this->config);
                break;

            /* 上传图片 */
            case 'uploadimage':
                /* 上传涂鸦 */
            case 'uploadscrawl':
                /* 上传视频 */
            case 'uploadvideo':
                /* 上传文件 */
            case 'uploadfile':
                $result = $this->_upload();
                break;

            /* 列出图片 */
            case 'listimage':
                $result = $this->_list();
                break;
            /* 列出文件 */
            case 'listfile':
                $result = $this->_list();
                break;

            /* 抓取远程文件 */
            case 'catchimage':
                $result = $this->_crawler();
                break;

            default:
                $result = json_encode([
                    'state' => '请求地址出错',
                ]);
                break;
        }

        /* 输出结果 */
        if ($this->request->param('callback')) {
            if (preg_match("/^[\w_]+$/", $this->request->param('callback'))) {
                echo htmlspecialchars($this->request->param('callback')) . '(' . $result . ')';
            } else {
                return json_encode([
                    'state' => 'callback参数不合法',
                ]);
            }
        } else {
            return $result;
        }
    }

    /**
     * 上传图片
     */
    private function _upload()
    {
        /* 上传配置 */
        $base64    = 'upload';
        $fieldName = '';
        $action    = $this->request->param('action');

        switch ($action) {
            case 'uploadimage':
                $config    = [
                    "pathFormat" => $this->config['imagePathFormat'],
                    "maxSize"    => $this->config['imageMaxSize'],
                    "allowFiles" => $this->config['imageAllowFiles'],
                ];
                $fieldName = $this->config['imageFieldName'];
                break;
            case 'uploadscrawl':
                $config    = [
                    "pathFormat" => $this->config['scrawlPathFormat'],
                    "maxSize"    => $this->config['scrawlMaxSize'],
                    "allowFiles" => $this->config['scrawlAllowFiles'],
                    "oriName"    => "scrawl.png",
                ];
                $fieldName = $this->config['scrawlFieldName'];
                $base64    = "base64";
                break;
            case 'uploadvideo':
                $config    = [
                    "pathFormat" => $this->config['videoPathFormat'],
                    "maxSize"    => $this->config['videoMaxSize'],
                    "allowFiles" => $this->config['videoAllowFiles'],
                ];
                $fieldName = $this->config['videoFieldName'];
                break;
            case 'uploadfile':
            default:
                $config    = [
                    "pathFormat" => $this->config['filePathFormat'],
                    "maxSize"    => $this->config['fileMaxSize'],
                    "allowFiles" => $this->config['fileAllowFiles'],
                ];
                $fieldName = $this->config['fileFieldName'];
                break;
        }


        /* 生成上传实例对象并完成上传 */
        $up = new Uploader($fieldName, $config, $base64);

        /**
         * 得到上传文件所对应的各个参数,数组结构
         * array(
         *     "state" => "",          //上传状态，上传成功时必须返回"SUCCESS"
         *     "url" => "",            //返回的地址
         *     "title" => "",          //新文件名
         *     "original" => "",       //原始文件名
         *     "type" => ""            //文件类型
         *     "size" => "",           //文件大小
         * )
         */

        /* 返回数据 */
        return json_encode($up->getFileInfo());

    }

    /**
     * 列出图片/文件
     */
    private function _list()
    {
        /* 判断类型 */
        $action = $this->request->param('action');
        switch ($action) {
            /* 列出文件 */
            case 'listfile':
                $allowFiles = $this->config['fileManagerAllowFiles'];
                $listSize   = $this->config['fileManagerListSize'];
                $path       = $this->config['fileManagerListPath'];
                break;
            /* 列出图片 */
            case 'listimage':
            default:
                $allowFiles = $this->config['imageManagerAllowFiles'];
                $listSize   = $this->config['imageManagerListSize'];
                $path       = $this->config['imageManagerListPath'];
        }
        $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

        /* 获取参数 */
        $size  = $this->request->param('size', 0, 'htmlspecialchars');
        $start = $this->request->param('start', 0, 'htmlspecialchars');
        $size  = $size ? $size : $listSize;
        $end   = $start + $size;

        /* 获取文件列表 */
        $path  = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "" : "/") . $path;
        $files = getfiles($path, $allowFiles);
        if (!count($files)) {
            return json_encode([
                "state" => "no match file",
                "list"  => [],
                "start" => $start,
                "total" => count($files),
            ]);
        }

        /* 获取指定范围的列表 */
        $len = count($files);
        for ($i = min($end, $len) - 1, $list = []; $i < $len && $i >= 0 && $i >= $start; $i--) {
            $list[] = $files[$i];
        }
        //倒序
        //for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){
        //    $list[] = $files[$i];
        //}

        /* 返回数据 */
        $result = json_encode([
            "state" => "SUCCESS",
            "list"  => $list,
            "start" => $start,
            "total" => count($files),
        ]);

        return $result;
    }

    /**
     * 抓取远程文件
     */
    private function _crawler()
    {
        /* 上传配置 */
        $config    = [
            "pathFormat" => $this->config['catcherPathFormat'],
            "maxSize"    => $this->config['catcherMaxSize'],
            "allowFiles" => $this->config['catcherAllowFiles'],
            "oriName"    => "remote.png",
        ];
        $fieldName = $this->config['catcherFieldName'];

        /* 抓取远程图片 */
        $list = [];
        if (isset($_POST[$fieldName])) {
            $source = $_POST[$fieldName];
        } else {
            $source = $_GET[$fieldName];
        }
        foreach ($source as $imgUrl) {
            $item = new Uploader($imgUrl, $config, "remote");
            $info = $item->getFileInfo();
            array_push($list, [
                "state"    => $info["state"],
                "url"      => $info["url"],
                "size"     => $info["size"],
                "title"    => htmlspecialchars($info["title"]),
                "original" => htmlspecialchars($info["original"]),
                "source"   => htmlspecialchars($imgUrl),
            ]);
        }

        /* 返回抓取数据 */
        return json_encode([
            'state' => count($list) ? 'SUCCESS' : 'ERROR',
            'list'  => $list,
        ]);
    }
}